import {Component, ElementRef} from '@angular/core';
import {AlertController, IonicPage, NavController, NavParams, ToastController} from 'ionic-angular';
import {LoginPage} from "../login";
import {UnlockService} from '../../../services/native/authentication/authentication.service';


@IonicPage()
@Component({
    selector: 'page-graphic-login',
    templateUrl: 'graphic-login.html',
})


export class GraphicLoginPage {
    height: number;  //画布高度*/
    width: number;  //画布宽度
    chooseType: number = 3;//每行手势密码个数
    devicePixelRatio: number;
    bigCtx: any;
    lastPoint: any;
    restPoint: any[];
    r: number; //圆半径
    empty: number; //圆之间的空隙
    arr: any[]; //记录圆的索引及半径
    canvas: HTMLCanvasElement;
    touchFlag: boolean;
    clockTime: number = 5;//解锁试错次数

    warnInnerColor: string = '#cacaca';//错误警告内圆颜色
    warnBorderColor: string = '#cacaca';//错误警告线颜色

    initFillColor: string = 'rgba(219, 246, 245, 0.3)'; //初始化填充颜色
    initBorderColor: string = '#ffffff';//初始化边框颜色

    normalInnerColor: string = '#ffffff'; //绘图内圆颜色

    normalLineColor: string = '#60b587';
    lineWidth: number = 3; //连线宽度
    borderWidth: number;//圆圈边框宽度

    graphMarginTop: string;

    constructor(public navCtrl: NavController, public navParams: NavParams,
                private alertCtrl: AlertController,
                private toastCtrl: ToastController,
                private _elementRef: ElementRef,
                private unlockService: UnlockService) {
    }

    ionViewDidLoad() {
        console.log("2222")
    }

    ionViewDidEnter() {
        console.log("3333")
        let container = this._elementRef.nativeElement.querySelector('div.container');
        let testDiv = this._elementRef.nativeElement.querySelector('div.scroll-content');
        let pageHeight = testDiv.offsetHeight;
        //减去logon
        this.graphMarginTop = ((pageHeight - 250) * 100 / 2 / 1080) + 'vw';
        this.init({
            width: container.offsetWidth,
            height: container.offsetHeight
        });
        this.navCtrl.swipeBackEnabled = false;
    }

    init(obj) {
        this.width = obj.width;
        this.devicePixelRatio = 1;
        this.r = this.convertToCurrentSize(75);
        this.empty = this.convertToCurrentSize(100);
        this.borderWidth = this.convertToCurrentSize(2);
        this.initCanvas();
        this.lastPoint = [];
        this.touchFlag = false;
        this.canvas = document.getElementById('lockCanvas') as HTMLCanvasElement;
        this.bigCtx = this.canvas.getContext('2d');
        this.createBigCircle(this.bigCtx, this.r);
        this.bindEvent();
    }

    /*初始化两个画布的宽度与高度*/
    initCanvas() {
        let canvas = document.getElementById('lockCanvas');
        let width = this.width || 320;
        let height = width - 2 * this.r;
        canvas.style.width = width + 'px';
        canvas.style.height = height + 'px';
        canvas['width'] = width * this.devicePixelRatio;
        canvas['height'] = height * this.devicePixelRatio;
    }


    /*绘制单个圆*/
    drawCle(ctx, x, y, r) {
        ctx.beginPath();//画圆圈
        ctx.strokeStyle = this.initBorderColor;//圆圈默认的颜色
        ctx.lineWidth = this.borderWidth;
        ctx.arc(x, y, r, 0, Math.PI * 2, true);
        ctx.stroke();
        ctx.beginPath();//画实心圆
        ctx.arc(x, y, r, 0, Math.PI * 2, true);
        ctx.fillStyle = this.initFillColor;
        ctx.fill();
        ctx.stroke();
    }

    /*绘制手势大圆圈*/
    createBigCircle(ctx, defineR) {
        let n = this.chooseType;
        let count = 0;
        let marginLeft = (ctx.canvas.width - 6 * defineR - 2 * this.empty) / 2;
        this.lastPoint = [];
        this.arr = [];
        this.restPoint = [];

        for (let i = 0; i < n; i++) {
            for (let j = 0; j < n; j++) {
                count++;
                let obj = {
                    x: marginLeft + (j * 2 + 1) * defineR + j * this.empty,
                    y: 5 + (i * 2 + 1) * defineR + i * this.empty,
                    index: count
                };
                this.arr.push(obj);
                this.restPoint.push(obj);
            }
        }
        ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
        for (let i = 0; i < this.arr.length; i++) {
            this.drawCle(ctx, this.arr[i].x, this.arr[i].y, defineR);
        }
    }

    getPosition(e) {
        let rect = e.currentTarget.getBoundingClientRect();
        return {
            x: (e.touches[0].clientX - rect.left) * this.devicePixelRatio,
            y: (e.touches[0].clientY - rect.top) * this.devicePixelRatio
        };
    }

    storePass(psw) {
        let smallTipMsg = document.getElementById('smallTipMsg');
        smallTipMsg.style.display = 'none';

        //登录验证密码
        if (psw.length < 4) {
            this.drawPointAndLine(this.initFillColor, this.warnInnerColor, this.warnBorderColor, '请至少连接4个点');
            return;
        }
        let storePwd = [];
        psw.forEach((item) => {
            storePwd.push({index: item.index})
        });
        this.unlockService.validateGraphic(JSON.stringify(storePwd)).then(res => {
            if (res) {
                this.unlockService.updateGraphicErrorTimes();
                this.navCtrl.setRoot('TabsPage');
            } else {
                this.dealErrorLock();
            }
        });
    }

    /*密码解锁错误处理*/
    dealErrorLock() {
        this.unlockService.graphicErrorTimes().then(errorTime => {
            let saveTime = this.clockTime - errorTime;
            if (saveTime <= 0) {
                this.promptReLogin("手势密码错误已达上限，请重新登录");
            } else {

                this.drawPointAndLine(this.initFillColor, this.warnInnerColor, this.warnBorderColor, `手势密码错误，还可以绘制${saveTime}次`);
            }
        });
    }

    drawPointAndLine(outStyle = '', innerStyle = '', borderStyle = '', tipMsg) {
        this.drawLine(borderStyle, this.lastPoint[this.lastPoint.length - 1]);// 每帧画圆
        this.drawPoint(outStyle, innerStyle);
        let title = document.getElementById('tipMsg');
        title.style.display = 'none';
        let smalltitle = document.getElementById('smallTipMsg');
        smalltitle.innerHTML = tipMsg;
        smalltitle.style.display = "block";
    }

    /**
     * 绘制圆
     * @param {string} outStyle 外圈圆颜色
     * @param {string} innerStyle 内圈圆颜色
     */
    drawPoint(outStyle = '', innerStyle = '') {
        for (let i = 0; i < this.lastPoint.length; i++) {
            this.bigCtx.lineWidth = 2;
            this.bigCtx.beginPath();
            this.bigCtx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r, 0, Math.PI * 2, true);
            this.bigCtx.closePath();
            this.bigCtx.fillStyle = outStyle;
            this.bigCtx.fill();//画实心圆
        }
        for (let i = 0; i < this.lastPoint.length; i++) {
            this.bigCtx.fillStyle = innerStyle;
            this.bigCtx.beginPath();
            this.bigCtx.arc(this.lastPoint[i].x, this.lastPoint[i].y, this.r / 2.5, 0, Math.PI * 2, true);
            this.bigCtx.closePath();
            this.bigCtx.fill();
        }
    }

    drawLine(style, po) {
        this.bigCtx.beginPath();
        this.bigCtx.strokeStyle = style;
        this.bigCtx.lineWidth = this.lineWidth;
        if (!this.lastPoint[0]) {
            return;
        }
        this.bigCtx.moveTo(this.lastPoint[0].x, this.lastPoint[0].y);

        for (let i = 1; i < this.lastPoint.length; i++) {
            this.bigCtx.lineTo(this.lastPoint[i].x, this.lastPoint[i].y);
        }
        this.bigCtx.lineTo(po.x, po.y);
        this.bigCtx.stroke();
        this.bigCtx.closePath();
    }

    update(po) {
        this.bigCtx.clearRect(0, 0, this.bigCtx.canvas.width, this.bigCtx.canvas.height);
        this.drawLine(this.normalLineColor, po);// 先画连接线 后画圆形，这样可以进行覆盖

        for (let i = 0; i < this.arr.length; i++) {
            this.drawCle(this.bigCtx, this.arr[i].x, this.arr[i].y, this.r);
        }
        this.drawPoint(this.initFillColor, this.normalInnerColor);// 每帧花轨迹
        //this.drawStatusPoint(this.clockCircleColor);// 每帧花轨迹
        for (let i = 0; i < this.restPoint.length; i++) {
            if (Math.abs(po.x - this.restPoint[i].x) < this.r && Math.abs(po.y - this.restPoint[i].y) < this.r) {
                this.drawPoint(this.initFillColor, this.normalInnerColor);
                this.lastPoint.push(this.restPoint[i]);
                this.restPoint.splice(i, 1);
                break;
            }
        }
    }

    /*重绘圆形按钮*/
    reset() {
        this.createBigCircle(this.bigCtx, this.r);
    }

    /*绑定 手势拖拽 信息*/
    bindEvent() {
        let self = this;
        this.canvas.addEventListener('touchstart', function (e) {
            e.preventDefault();// 某些android 的 touchmove不宜触发 所以增加此行代码
            self.lastPoint=[];
            let po = self.getPosition(e);
            for (let i = 0; i < self.arr.length; i++) {
                if (Math.abs(po.x - self.arr[i].x) < self.r && Math.abs(po.y - self.arr[i].y) < self.r) {
                    self.touchFlag = true;
                    self.drawPoint(self.initFillColor, self.normalInnerColor);
                    self.lastPoint.push(self.arr[i]);
                    self.restPoint.splice(i, 1);
                    break;
                }
            }
        }, false);
        this.canvas.addEventListener('touchmove', function (e) {
            if (self.touchFlag) {
                self.update(self.getPosition(e));
            }
        }, false);
        this.canvas.addEventListener('touchend', function () {
            if (self.touchFlag) {
                self.touchFlag = false;
                self.storePass(self.lastPoint);
                setTimeout(() => {
                    self.reset();
                }, 1000)
            }
        }, false);
    }

    passwordLogIn() {
        this.navCtrl.push('LoginPage');
    }

    //单位换算
    convertToCurrentSize(x: number) {
        return (this.width * x) / 1080;
    }

    //重新登录
    private promptReLogin(message) {
        //先退出并跳转到登录页，然后提示
        location.hash = '#/login';
        setTimeout(() => {
            let toast = this.alertCtrl.create({
                message: message,
                cssClass:"custom-alert",
                buttons:[{
                    text:'确定',
                    handler:()=>{
                        location.hash = '#/login';
                    }
                }]
            });
            toast.present();
        }, 500);
        localStorage.setItem('ReLoginFlag', "true");
    }
}
